package com.easemob.chatuidemo.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import com.easemob.chatuidemo.R;
import com.easemob.chatuidemo.domain.Nearby;
import com.easemob.chatuidemo.service.GpsService;
import com.easemob.chatuidemo.service.UserService;
import com.easemob.chatuidemo.utils.Gps;
import com.easemob.chatuidemo.utils.GpsUtilsTool;
import com.easemob.chatuidemo.utils.SharedPreferencesUtil;
import com.easemob.chatuidemo.video.util.AsyncTask;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by pc on 15-5-29.
 */
public class NearbyActivity extends BaseActivity {
    private String nearby_kind;
    private TextView title;
    private ListView lv_nearby;
    private Button refresh;
    private int nearby;
    private List<Nearby> datas;
    private ListAdapter adapter;
    private Gps gps;
    private MyReceiver receiver=null;

    private String lat;
    private String lon;

    private ProgressDialog progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nearby);
        nearby = getIntent().getExtras().getInt("nearby");
        switch (nearby) {
            case 0:
                nearby_kind = this.getString(R.string.discover_tv_nearby);
                break;
            case 1:
                nearby_kind = this.getString(R.string.discover_tv_nearby_driver);
                break;
            case 2:
                nearby_kind = this.getString(R.string.discover_tv_nearby_wuliu);
                break;
            case 3:
                nearby_kind = this.getString(R.string.discover_tv_nearby_master);
                break;
            case 4:
                nearby_kind = this.getString(R.string.discover_tv_nearby_supplier);
                break;
        }
        title = (TextView) findViewById(R.id.message_title);
        title.setText(nearby_kind);

        lv_nearby = (ListView) findViewById(R.id.listview_nearby);
        adapter = new ListAdapter(NearbyActivity.this);
        lv_nearby.setAdapter(adapter);
        lv_nearby.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
                String uid = datas.get(position).getuId();
                String upic = datas.get(position).getTouxiang();
                String name = datas.get(position).getMingcheng();
                String juli = datas.get(position).getJuli();
                String location = datas.get(position).getDizhi();
                String infos = datas.get(position).getTel();
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("uid",uid);
                bundle.putString("nearby_kind",nearby_kind);
                bundle.putInt("nearby",nearby);
//                bundle.putString("upic",upic);
//                bundle.putString("name",name);
//                bundle.putString("juli",juli);
//                bundle.putString("location",location);
//                bundle.putString("infos",infos);
//                bundle.putString("kind",nearby_kind);
                intent.setClass(NearbyActivity.this, NearbyDetailsActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

//        refresh = (Button) findViewById(R.id.btn_refresh);


        if (!GpsUtilsTool.isGpsEnabled((LocationManager) getSystemService(Context.LOCATION_SERVICE))) {
            Toast.makeText(this, "GSP当前已禁用，请在您的系统设置屏幕启动。", Toast.LENGTH_LONG).show();
            Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(callGPSSettingIntent);
            return;
        }

        //启动服务
        startService(new Intent(this, GpsService.class));

        //注册广播
        receiver=new MyReceiver();
        IntentFilter filter=new IntentFilter();
        filter.addAction("com.ljq.activity.GpsService");
        registerReceiver(receiver, filter);
//        else {
//            gps = new Gps(this);
//            Location location = gps.getLocation();
//            if (location!=null){
//
//            } else {
//                Toast.makeText(this, "获取位置信息失败", Toast.LENGTH_SHORT).show();
//                finish();
//                return;
//            }
//
//        }

        new getNearbyNetWorek().execute(String.valueOf(nearby), SharedPreferencesUtil.get("loginname"),
                SharedPreferencesUtil.get("lat") ,SharedPreferencesUtil.get("lon"));
        Toast.makeText(NearbyActivity.this, "Location:lat=" + SharedPreferencesUtil.get("lat")
                + " ;lon=" + SharedPreferencesUtil.get("lon"), Toast.LENGTH_SHORT).show();
    }


    //获取广播数据
    private class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle=intent.getExtras();
            String lon=bundle.getString("lon");
            String lat=bundle.getString("lat");
            if(lon!=null&&!"".equals(lon)&&lat!=null&&!"".equals(lat)){

//                lat = String.valueOf(location.getLatitude());
//                lon = String.valueOf(location.getLongitude());
                new sendLocationNetWork().execute(SharedPreferencesUtil.get("uid"),lat,lon);
                SharedPreferencesUtil.put("lat",lat);
                SharedPreferencesUtil.put("lon",lon);

//                double distance=getDistance(Double.parseDouble(lat),
//                        Double.parseDouble(lon), homeLat, homeLon);
//                editText.setText("目前经纬度\n经度："+lon+"\n纬度："+lat+"\n离宿舍距离："+java.lang.Math.abs(distance));
            }else{
//                editText.setText("目前经纬度\n经度："+lon+"\n纬度："+lat);
            }
        }
    }

    private void refresh(View view){
        new getNearbyNetWorek().execute(String.valueOf(nearby), SharedPreferencesUtil.get("loginname"),
                SharedPreferencesUtil.get("lat") ,SharedPreferencesUtil.get("lon"));
        Toast.makeText(NearbyActivity.this, "Location:lat=" + SharedPreferencesUtil.get("lat")
                + " ;lon=" + SharedPreferencesUtil.get("lon"), Toast.LENGTH_SHORT).show();
    }

    private double getDistance(double lat1, double lon1, double lat2, double lon2) {
        float[] results = new float[1];
        Location.distanceBetween(lat1, lon1, lat2, lon2, results);
        return results[0];
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    public class ListAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        int count = 0;

        public ListAdapter(Context context) {
            this.mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            if (datas != null) {
                return datas.size();
            }
            return count;
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;

            if (null == convertView) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.nearby_item, null);

                holder.img = ((ImageView) convertView.findViewById(R.id.iv_nearby_item_pic));
                holder.nickname = ((TextView) convertView.findViewById(R.id.tv_nearby_name));
                holder.juli = ((TextView) convertView.findViewById(R.id.tv_nearby_juli));

                convertView.setTag(holder);

            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.nickname.setText(datas.get(position).getMingcheng());
            holder.juli.setText(datas.get(position).getJuli());

            imageLoader.displayImage(datas.get(position).getTouxiang(), holder.img);
            return convertView;
        }
    }


    public final class ViewHolder {
        public ImageView img;
        public TextView nickname;
        public TextView juli;
    }

    void progressDialogInit(){
        progressDialog = new ProgressDialog(this);
        progressDialog.setIcon(android.R.drawable.ic_menu_info_details);
        progressDialog.setTitle("正在获取数据");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("请稍后...");
    }

    public class getNearbyNetWorek extends AsyncTask<String ,Integer ,List<Nearby>> {

        @Override
        protected void onPreExecute() {
            progressDialogInit();
            progressDialog.show();
            super.onPreExecute();
        }

        @Override
        protected List<Nearby> doInBackground(String... params) {
            UserService userService = new UserService();
            datas = userService.queryNearbyInfo(params[0],params[1],params[2],params[3]);
            return datas;
        }

        @Override
        protected void onPostExecute(List<Nearby> result) {
            if (result == null)
            {
                progressDialog.dismiss();
                Toast.makeText(NearbyActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
            }
            if (result.size()>0){
                if (result.get(0).getRedCode() != "0000" ||!"0000".equals(result.get(0).getRedCode()))
                {
                    Toast.makeText(NearbyActivity.this, "获取数据出错，请稍候再试", Toast.LENGTH_SHORT).show();
                }
                else {
                    progressDialog.dismiss();
                    adapter = new ListAdapter(NearbyActivity.this);
                    lv_nearby.setAdapter(adapter);
                }
            } else {
                Toast.makeText(NearbyActivity.this, "暂无附近的人", Toast.LENGTH_SHORT).show();
            }


            progressDialog.dismiss();
            super.onPostExecute(result);
        }
    }

    private Map<String, String> getLocation(){

        Map<String,String> locationMap = new HashMap<String, String>();
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if(location != null){
                locationMap.put("lat",String.valueOf(location.getLatitude()));
                locationMap.put("lon",String.valueOf(location.getLongitude()));
            }
        }else{
            LocationListener locationListener = new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {

                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {

                }

                @Override
                public void onProviderEnabled(String s) {

                }

                @Override
                public void onProviderDisabled(String s) {

                }
            };
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000, 0,locationListener);
            Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if(location != null){
                locationMap.put("lat",String.valueOf(location.getLatitude()));
                locationMap.put("lon",String.valueOf(location.getLongitude()));
            }
        }

        return locationMap;
    }


    class sendLocationNetWork extends AsyncTask<String, Integer, String>{
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            UserService userService = new UserService();
            String redCode = userService.sendLocation(params[0],params[1],params[2]);
            return redCode;
        }

        @Override
        protected void onPostExecute(String result) {
            if ("100".equals(result)){
                Log.i("LocationService", "定位成功");
            }
            super.onPostExecute(result);
        }
    }

}
